package com.tmptSource.service.impl;

import com.tmpt.beans.A2User;
import com.tmpt.dto.Result;
import com.tmpt.others.jpush.JpushUtils;
import com.tmpt.others.jpush.PushtoSingle;
import com.tmpt.utils.DateTool;
import com.tmpt.service.impl.DataLimitService;
import com.tmpt.utils.StringUtils;
import com.tmpt.wf.WfDemo;
import com.tmptSource.bean.*;
import com.tmptSource.dto.*;
import com.tmptSource.enums.OwTaskStatus;
import com.tmptSource.enums.OwUserSupportType;
import com.tmptSource.mapper.*;
import com.tmptSource.service.intf.IOwTaskAnswerService;
import com.tmptSource.service.intf.IOwTaskService;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tmptSource.utils.dozer.MyMapper;
import com.tmptSource.utils.page.MyPageUtils;

import java.sql.Timestamp;
import java.util.*;

import org.dozer.Mapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created by wxy on 2016/7/28.
 */
@Service(value="owTaskService")
@Transactional(propagation = Propagation.REQUIRED)
public class OwTaskService implements IOwTaskService {


    private Logger log = Logger.getLogger(this.getClass());

    @Autowired private DataLimitService dataLimitService;
    @Autowired private Mapper mapper;
    @Autowired private MyMapper myMapper;
    @Autowired private MyPageUtils myPageUtils;
    @Autowired
    private OwTaskMapper owTaskMapper;
    @Autowired
    private OwPictureMagMapper owPictureMagMapper;
    @Autowired
    private OwWftaskUserLinkMapper owWftaskUserLinkMapper;
    @Autowired
    private A2userMapper a2userMapper;
    @Autowired
    private OwTaskAnswerMapper owTaskAnswerMapper;
    @Resource
    private IOwTaskAnswerService owTaskAnswerService;


    @Override
    public Result<OwTaskDto> pagination(OwTaskDto owTaskDto,PageDto pageDto) {
        //分页查询
        Result<OwTaskDto> result = myPageUtils.pagination(
                owTaskDto,pageDto,
                OwTask.class,
                OwTaskDto.class,
                owTaskMapper,
                false,null);

        return result;
    }

    @Override
    public Result<OwTaskDto> paginationWithoutLogin(OwTaskDto owTaskDto, PageDto pageDto) {
        //分页查询
        Result<OwTaskDto> result = myPageUtils.paginationWithoutLogin(
                owTaskDto,pageDto,
                OwTask.class,
                OwTaskDto.class,
                owTaskMapper,
                false,null);

        return result;
    }

    /**
    * 分布查询，有数据边界控制功能
    * @param owTaskDto
    * @param pageDto
    * @param paramMap
    * @return
    */
    @Override
    public Result<OwTaskDto> pagination(OwTaskDto owTaskDto,PageDto pageDto,Map<String,Object> paramMap) {
        //数据边界控制参数
        Map<String,Object> paramMap1 = dataLimitService.getLimitParam(paramMap);

        //分页查询
        Result<OwTaskDto> result = myPageUtils.pagination(
                owTaskDto, pageDto,
                OwTask.class,
                OwTaskDto.class,
                owTaskMapper,
                paramMap1,
                false, null);

        return result;
    }


    @Override
    public Result<OwTaskDto> selectAll() {
        Result<OwTaskDto> result = new Result();

        //排序
        PageDto pageDto = new PageDto();
        pageDto.setSortColumn("id");
        pageDto.setSortOrder("desc");
        Map<String,Object> mapParam = new HashMap<>();
        mapParam.put("page",pageDto);

        List<OwTask> list = owTaskMapper.selectAll(mapParam);
        List<OwTaskDto> dtoList = myMapper.map(list, OwTaskDto.class);
        result.setResultList(dtoList);

        return result.success();
    }

    @Override
    public Result<OwTaskDto> selectById(long id) {
        Result<OwTaskDto> result = new Result();

        OwTask owTask = owTaskMapper.selectById(id);
        if(owTask == null){
            return result.fault();
        }
        OwTaskDto dto = mapper.map(owTask, OwTaskDto.class);
        result.setResultObj(dto);

        return result.success();
    }


    /**
        返回ID值
    */
    @Override
    public Result<OwTaskDto> addData(OwTaskDto owTaskDto){
        Result<OwTaskDto> result = new Result();

        //封闭数据
        OwTask owTask = mapper.map(owTaskDto, OwTask.class);
        owTask.setCreatedate(DateTool.getCurTimestamp());

        //调用mapper
        long i = owTaskMapper.insert(owTask);
        if(i==0){
            return result.fault("插入失败");
        }


        //插入多张图片
        if(owTaskDto!=null && owTaskDto.getOwPictureMagDtoList()!=null) {
            for (OwPictureMagDto owPictureMagDto : owTaskDto.getOwPictureMagDtoList()) {
                OwPictureMag owPictureMag = mapper.map(owPictureMagDto, OwPictureMag.class);
                //1:front, 2:back （默认设1）
                owPictureMag.setFrontBackSort(
                        StringUtils.isNull(owPictureMagDto.getFrontBackSort())?1:Integer.parseInt(owPictureMagDto.getFrontBackSort()));
                owPictureMag.setOwTableType("ow_task_id");
                owPictureMag.setOwTableId(owTask.getId());
                owPictureMag.setCompanyId(0);
                owPictureMag.setCreatemanId(0);
                owPictureMag.setModifymanId(0);
                owPictureMag.setCreatedate(DateTool.getCurTimestamp());
                owPictureMagMapper.insert(owPictureMag);
            }
        }

        OwTaskDto dto = mapper.map(owTask,OwTaskDto.class);
        result.setResultObj(dto);

        return result.success();
    }

    /**
        返回ID值
    */
    @Override
    public Result<OwTaskDto> editData(OwTaskDto owTaskDto) {
        Result<OwTaskDto> result = new Result();

        //封装数据
        OwTask owTask = mapper.map(owTaskDto, OwTask.class);
        owTask.setModifydate(DateTool.getCurTimestamp());

        //调用mapper
        long i = owTaskMapper.updateById(owTask);
        if(i==0){
            return result.fault("编辑数据失败");
        }

        OwTaskDto dto = mapper.map(owTask,OwTaskDto.class);
        result.setResultObj(dto);

        return result.success();
    }


    /**
     * 修改任务状态
     * @param paramMap
     * @return
     */
    @Override
    public Result updateTaskStatusById(Map<String,Object> paramMap){
        Result<OwTaskDto> result = new Result();

        //封装数据
        OwTask owTask = new OwTask();
        owTask.setId(Long.parseLong(paramMap.get("id").toString()));
        owTask.setId(Long.parseLong(paramMap.get("owTaskStatus").toString()));

        //调用mapper
        long i = owTaskMapper.updateTaskStatusById(owTask);
        if(i==0){
            return result.fault("修改任务状态失败");
        }

        return result.success();

    }

    /**
    伪删除记录，返回ID值
    */
    @Override
    public Result deleteById(long id,String adminMan){
        Result result = new Result();

        Map<String,Object> mapParameter = new HashMap();
        mapParameter.put("id", id);
        mapParameter.put("modifyman", adminMan);
        mapParameter.put("modifydate",DateTool.getCurTimestamp());

        //调用mapper
        long i = owTaskMapper.deleteById(mapParameter);
        if(i==0){
            return result.fault("删除数据失败");
        }

        return result.success();
    }



    /**
     *页面上查询列的值，动态加载，sql语句读数据库配置而来
     */
    @Override
    public java.util.List select4mainManId(){
        return owTaskMapper.select4mainManId();
    }

    /**
     *页面上查询列的值，动态加载，sql语句读数据库配置而来
     */
    @Override
    public java.util.List select4assistManId(){
        return owTaskMapper.select4assistManId();
    }



    //===========================================
    //       工作流管理
    //===========================================

    @Resource
    WfDemo wfDemo;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private OwIssueDeclareMapper owIssueDeclareMapper;
    @Autowired
    private OwExecuteRecordMapper owExecuteRecordMapper;

    /**
     * 添加数据并生成任务->分配任务 for double random
     返回ID值
     */
    @Override
    public Result<OwTaskDto> addDataAndAssign4DoubleRandom(OwTaskDto owTaskDto){
        Result<OwTaskDto> result = new Result();
        Map<String,Object> paramMap = new HashMap<>();

        //插入任务（Bussiness）
        result = addData(owTaskDto);
        OwTaskDto owTaskDto1 = result.getResultObj();

        //workflow parameter
        paramMap.put("owTaskId",owTaskDto1.getId());
        paramMap.put("userId",owTaskDto1.getCreatemanId());
        paramMap.put("username", owTaskDto1.getCreateman());
        paramMap.put("companyId", owTaskDto1.getCompanyId());
        String mainManId = owTaskDto.getMainManId();
        List<Map<String,Object>> userList = new ArrayList<>();
        List<String> mainManIdList = new ArrayList<>();
        if(!StringUtils.isNull(mainManId)) {
            mainManIdList = Arrays.asList(mainManId.split(","));
            for (String mainManId1 : mainManIdList) {
                Map<String, Object> map = new HashMap<>();
                map.put("userId", mainManId1.trim());
                map.put("owUserSupportType", OwUserSupportType.Main.getKeyName());
                userList.add(map);
            }
        }
        paramMap.put("userList", userList);

        //分配任务(WorkFlow)
        assignTaskWF(paramMap);

        return result.success();
    }

    /**
     * 添加数据并生成任务->分配任务
     返回ID值
     */
    @Override
    public Result<OwTaskDto> addDataAndAssign(OwTaskDto owTaskDto, Map<String,Object> paramMap){
        Result<OwTaskDto> result = new Result();

        //插入任务（Bussiness）
        result = addData(owTaskDto);
        OwTaskDto owTaskDto1 = result.getResultObj();

        //workflow parameter
        paramMap.put("owTaskId",owTaskDto1.getId());
        paramMap.put("userId",owTaskDto1.getCreatemanId());
        paramMap.put("username", owTaskDto1.getCreateman());
        paramMap.put("companyId", owTaskDto1.getCompanyId());
        String mainManId = owTaskDto1.getMainManId();
        String assistManId = owTaskDto1.getAssistManId();
        List<Map<String,Object>> userList = new ArrayList<>();
        List<String> mainManIdList = new ArrayList<>();
        if(!StringUtils.isNull(mainManId)) {
            mainManIdList = Arrays.asList(mainManId.split(","));
            for (String mainManId1 : mainManIdList) {
                Map<String, Object> map = new HashMap<>();
                map.put("userId", mainManId1.trim());
                map.put("owUserSupportType", OwUserSupportType.Main.getKeyName());
                userList.add(map);
            }
        }
        if(!StringUtils.isNull(assistManId)) {
            List<String> assistManIdList = Arrays.asList(assistManId.split(","));
            for (String assistManId1 : assistManIdList) {
                //判断协办人员是否存在主办中，存在就continue
                boolean existMainIdList = false;
                for (String mainManId1 : mainManIdList) {
                    if (mainManId1.equals(assistManId1.trim())) {
                        existMainIdList = true;
                    }
                }
                if (existMainIdList) {
                    continue;
                }
                //
                Map<String, Object> map = new HashMap<>();
                map.put("userId", assistManId1.trim());
                map.put("owUserSupportType", OwUserSupportType.Asister.getKeyName());
                userList.add(map);
            }
        }
        paramMap.put("userList", userList);

        //分配任务(WorkFlow)
        assignTaskWF(paramMap);

        //问题转任务：删除申报的问题，和执勤记录
        String owIssueDeclareIdStr = (String)paramMap.get("owIssueDeclareId");
        if(!StringUtils.isNull(owIssueDeclareIdStr)) {
            Map<String,Object> map = new HashMap<>();
            map.put("id",owIssueDeclareIdStr);
            map.put("modifyman", owTaskDto1.getCreatemanId());
            map.put("modifydate", DateTool.getCurTimestamp());
            owIssueDeclareMapper.deleteById(map);
            //删除执行计划
            map.clear();
            OwExecuteRecord owExecuteRecord = new OwExecuteRecord();
            owExecuteRecord.setBusinessTableName("ow_issue_declare");
            owExecuteRecord.setBusinessTableId(Long.parseLong(owIssueDeclareIdStr));
            map.put("bean", owExecuteRecord);
            List<OwExecuteRecord> owExecuteRecordList = owExecuteRecordMapper.selectAll(map);
            if(owExecuteRecordList.size()>0) {
                OwExecuteRecord  owExecuteRecord1 = owExecuteRecordList.get(0);
                Map<String, Object> map1 = new HashMap<>();
                map1.put("id", owExecuteRecord1.getId());
                map1.put("modifyman", owTaskDto1.getCreatemanId());
                map1.put("modifydate", DateTool.getCurTimestamp());
                owExecuteRecordMapper.deleteById(map1);
            }
        }

        return result.success();
    }

    /**
     分配任务
     */
    @Override
    public Result assignTaskWF(Map<String,Object> paramMap){
        Result result = new Result();
        //String owTaskId = (String)paramMap.get("taskId");
        String owTaskId = (String)paramMap.get("owTaskId");
        String userId = (String)paramMap.get("userId");
        String username = (String)paramMap.get("username");
        String companyId = (String)paramMap.get("companyId");
        List<Map<String,Object>> userList = (List<Map<String,Object>>)paramMap.get("userList");
        //String userIds = "";
        List<String> userIdList = new ArrayList<>();
        for(Map<String,Object> map : userList){
            String assUserId = (String)map.get("userId");
            String wfTaskId = startNewWFTask4User(assUserId,userId,owTaskId);
            //接收通知的用户ID
            String clientId = addWftaskUserLinkSingleUser(map, wfTaskId, owTaskId, userId, username, companyId);
            userIdList.add(clientId);
        }
        log.debug("=========>owTaskId:" + owTaskId);

        //发送Jpush
        PushtoSingle.push(userIdList,"您有待处理任务，请及时受理。");

        return result.success();
    }

    /**
     * 给用户起一个新任务
     * @param assUserId
     * @param authUserId
     * @return 工作流任务ID
     */
    private String startNewWFTask4User(String assUserId, String authUserId, String owTaskId){
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("userIds", assUserId);
        //variables.put("owTaskType", "1");
        identityService.setAuthenticatedUserId(authUserId);
        ProcessInstance processInstance =
                runtimeService.startProcessInstanceByKey("myTaskProcess1", "myTaskProcess:" + owTaskId, variables);
        log.debug("====>processInstanceId:" + processInstance.getId() + "   ActivityId:" + processInstance.getActivityId());

        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        String wfTaskId = task.getId();
        log.debug("=======>wfTaskId:" + wfTaskId);
        return wfTaskId;
    }

    /**
     * 返回接收通知的 ClientID
     * @param userMap
     * @param wfTaskId
     * @param owTaskId
     * @param createmanId
     * @param createmanName
     * @param companyId
     * @return
     */
    public String addWftaskUserLinkSingleUser(Map<String,Object> userMap, String wfTaskId, String owTaskId, String createmanId, String createmanName, String companyId ){
        String clientID = null;

        //创建业务系统中关联任务，为接收状态，发通知准备
        String assignUserId = (String)userMap.get("userId");
        String owUserSupportType = (String)userMap.get("owUserSupportType");
        Long userIdLng = Long.parseLong(assignUserId);
        Long wfTaskIdLng = Long.parseLong(wfTaskId);

        A2user a2user = a2userMapper.selectById(userIdLng);
        //userIdList.add(assUserId);
        if(a2user.getClientID()!=null) {
            clientID = a2user.getClientID();
        }
        //查询一下是否是：一个用户一个任务，别冲突了
        OwWftaskUserLink owWftaskUserLinkParam = new OwWftaskUserLink();
        owWftaskUserLinkParam.setA2userId(userIdLng);
        owWftaskUserLinkParam.setWfTaskId(wfTaskIdLng);
        Map<String,Object> paramMapSearch = new HashMap<>();
        paramMapSearch.put("bean", owWftaskUserLinkParam);
        int count = owWftaskUserLinkMapper.selectListCount(paramMapSearch);
        if(count>0){
            return null;
            //throw new RuntimeException("该任务已分配给用户ID："+userIdLng);
        }
        //插入
        owWftaskUserLinkParam.setHasReceiveTask(0);
        owWftaskUserLinkParam.setOwTaskId(Long.parseLong(owTaskId));
        owWftaskUserLinkParam.setIsFinished(0);
        owWftaskUserLinkParam.setOwUserSupportType(Integer.parseInt(owUserSupportType));
        owWftaskUserLinkParam.setCreatemanId(Integer.parseInt(createmanId));
        owWftaskUserLinkParam.setCreateman(createmanName);
        owWftaskUserLinkParam.setCompanyId(Integer.parseInt(companyId));
        owWftaskUserLinkParam.setModifymanId(0);
        owWftaskUserLinkParam.setCreatedate(DateTool.getCurTimestamp());
        owWftaskUserLinkMapper.insert(owWftaskUserLinkParam);

        return clientID;
    }

    public List<String> addWftaskUserLink(List<Map<String,Object>> userList, String wfTaskId, String owTaskId, String createmanId, String createmanName, String companyId ){
        //接收通知的用户ID
        List<String> userIdList = new ArrayList<>();

        //创建业务系统中关联任务，为接收状态，发通知准备
        for(Map<String,Object> map : userList){
            String assignUserId = (String)map.get("userId");
            String owUserSupportType = (String)map.get("owUserSupportType");
            Long userIdLng = Long.parseLong(assignUserId);
            Long wfTaskIdLng = Long.parseLong(wfTaskId);

            A2user a2user = a2userMapper.selectById(userIdLng);
            //userIdList.add(assUserId);
            if(a2user.getClientID()!=null) {
                userIdList.add(a2user.getClientID());
            }
            //查询一下是否是：一个用户一个任务，别冲突了
            OwWftaskUserLink owWftaskUserLinkParam = new OwWftaskUserLink();
            owWftaskUserLinkParam.setA2userId(userIdLng);
            owWftaskUserLinkParam.setWfTaskId(wfTaskIdLng);
            Map<String,Object> paramMapSearch = new HashMap<>();
            paramMapSearch.put("bean", owWftaskUserLinkParam);
            int count = owWftaskUserLinkMapper.selectListCount(paramMapSearch);
            if(count>0){
                continue;
                //throw new RuntimeException("该任务已分配给用户ID："+userIdLng);
            }
            //插入
            owWftaskUserLinkParam.setHasReceiveTask(0);
            owWftaskUserLinkParam.setOwTaskId(Long.parseLong(owTaskId));
            owWftaskUserLinkParam.setIsFinished(0);
            owWftaskUserLinkParam.setOwUserSupportType(Integer.parseInt(owUserSupportType));
            owWftaskUserLinkParam.setCreatemanId(Integer.parseInt(createmanId));
            owWftaskUserLinkParam.setCreateman(createmanName);
            owWftaskUserLinkParam.setCompanyId(Integer.parseInt(companyId));
            owWftaskUserLinkParam.setModifymanId(0);
            owWftaskUserLinkParam.setCreatedate(DateTool.getCurTimestamp());
            owWftaskUserLinkMapper.insert(owWftaskUserLinkParam);
        }

        return userIdList;
    }

    /**
     * 发送通知，未受理任务的通知一直发
     */
    @Override
    public Result timer4NoticeWaitingTask(Map<String,Object> paramMap1){
        Result result = new Result();

        log.debug("===============>timer4NoticeWaitingTask");
        OwWftaskUserLink owWftaskUserLink = new OwWftaskUserLink();
        owWftaskUserLink.setHasReceiveTask(0);
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("bean", owWftaskUserLink);
        List<OwWftaskUserLink> owWftaskUserLinkList = owWftaskUserLinkMapper.selectAll(paramMap);
        //接收通知的用户ID
        List<String> userIdList = new ArrayList<>();
        for(OwWftaskUserLink owWftaskUserLink1 : owWftaskUserLinkList){
            Long assUserId = owWftaskUserLink1.getA2userId();
            A2user a2user = a2userMapper.selectById(assUserId);
            //userIdList.add(""+assUserId);
            userIdList.add(a2user.getClientID());
        }
        //发送Jpush
        //JpushUtils.push(userIdList,"您有待处理任务，请及时受理。");
        PushtoSingle.push(userIdList,"您有待处理任务，请及时受理。");

        return result.success();
    }

    /**
     向任务组中加用户
     */
    @Override
    public Result addGroupUserWF(Map<String,Object> paramMap){
        Result result = new Result();

        String userId = (String)paramMap.get("userId");
        String username = (String)paramMap.get("username");
        String companyId = (String)paramMap.get("companyId");
        String owTaskId = (String)paramMap.get("taskId");
        //String wfTaskId = (String)paramMap.get("wfTaskId");
        List<String> mainManIdList = (List<String>)paramMap.get("mainManIdList");
        List<String> mainManNameList = (List<String>)paramMap.get("mainManNameList");
        List<String> assistManIdList = (List<String>)paramMap.get("assistManIdList");
        List<String> assistManNameList = (List<String>)paramMap.get("assistManNameList");
        //
        List<String> userIdList = new ArrayList<>();
        List<Map<String,Object>> userList4Check = new ArrayList<>();
        StringBuffer mainManIdSb = new StringBuffer();
        StringBuffer assistManIdSb = new StringBuffer();
        StringBuffer mainManNameSb = new StringBuffer();
        StringBuffer assistManNameSb = new StringBuffer();
        //check
        for(String userId1 : mainManIdList){
            Map<String,Object> map = new HashMap<>();
            map.put("userId",userId1);
            map.put("owUserSupportType", OwUserSupportType.Main.getKeyName());
            userList4Check.add(map);
        }
        //
        for(String userId1 : assistManIdList){
            Map<String,Object> map = new HashMap<>();
            map.put("userId",userId1);
            map.put("owUserSupportType", OwUserSupportType.Asister.getKeyName());
            userList4Check.add(map);
        }
        //check
        Result result1 = noUserBeenAssigned(userList4Check, owTaskId);
        if(!result1.isSuccess()){
            return result1;
            //throw new RuntimeException(result1.getContent());
        }

        //start task
        for(String userId1 : mainManIdList){
            String wfTaskIdNew = startNewWFTask4User(userId1, "0", owTaskId);
            Map<String,Object> map = new HashMap<>();
            map.put("userId",userId1);
            map.put("owUserSupportType",OwUserSupportType.Main.getKeyName());
            mainManIdSb.append(userId1).append(",");
            //接收通知的用户ID
            String clientId = addWftaskUserLinkSingleUser(map, wfTaskIdNew, owTaskId, userId, username, companyId);
            userIdList.add(clientId);
        }
        if(mainManIdSb.length()>0)mainManIdSb.deleteCharAt(mainManIdSb.length()-1);
        String mainManId = mainManIdSb.toString();
        //
        for(String userId1 : assistManIdList){
            String wfTaskIdNew = startNewWFTask4User(userId1,"0",owTaskId);
            Map<String,Object> map = new HashMap<>();
            map.put("userId",userId1);
            map.put("owUserSupportType", OwUserSupportType.Asister.getKeyName());
            assistManIdSb.append(userId1).append(",");
            //接收通知的用户ID
            String clientId = addWftaskUserLinkSingleUser(map, wfTaskIdNew, owTaskId, userId, username, companyId);
            userIdList.add(clientId);
        }
        if(assistManIdSb.length()>0)assistManIdSb.deleteCharAt(assistManIdSb.length()-1);
        String assistManId = assistManIdSb.toString();
        //
        for(String username1 : mainManNameList){
            mainManNameSb.append(username1).append(",");
        }
        if(mainManNameSb.length()>0)mainManNameSb.deleteCharAt(mainManNameSb.length()-1);
        String mainManName = mainManNameSb.toString();
        //
        for(String username1 : assistManNameList){
            assistManNameSb.append(username1).append(",");
        }
        if(assistManNameSb.length()>0)assistManNameSb.deleteCharAt(assistManNameSb.length()-1);
        String assistManName = assistManNameSb.toString();

        //修改任务列表，增加主办协办人员
        OwTask owTask = owTaskMapper.selectById(Long.parseLong(owTaskId));
        String mainManIdDB = owTask.getMainManId();
        String mainManNameDB = owTask.getMainManName();
        String assistManIdDB = owTask.getAssistManId();
        String assistManNameDB = owTask.getAssistManName();
        if(!StringUtils.isNull(mainManIdDB)){
            mainManId = mainManIdDB+","+mainManId;
            mainManName = mainManNameDB+","+mainManName;
        }
        if(!StringUtils.isNull(assistManIdDB)){
            assistManId = assistManIdDB+","+assistManId;
            assistManName = assistManNameDB+","+assistManName;
        }

        owTask.setMainManId(mainManId);
        owTask.setMainManName(mainManName);
        owTask.setAssistManId(assistManId);
        owTask.setAssistManName(assistManName);
        owTaskMapper.updateById(owTask);

        //发送Jpush
        PushtoSingle.push(userIdList,"您有待处理任务，请及时受理。");

        return result.success();
    }

    /**
     * 例如：app上分发任务给队员，队员是否已经正在执行这个任务了
     * @param userList
     */
    public Result noUserBeenAssigned(List<Map<String,Object>> userList, String owTaskId){
        Result result = new Result();

        Long owTaskIdLng = Long.parseLong(owTaskId);
        OwWftaskUserLink owWftaskUserLinkParam = new OwWftaskUserLink();
        owWftaskUserLinkParam.setOwTaskId(owTaskIdLng);
        Map<String, Object> paramMapSearch = new HashMap<>();
        paramMapSearch.put("bean", owWftaskUserLinkParam);
        List<OwWftaskUserLink> owWftaskUserLinkList = owWftaskUserLinkMapper.selectAll(paramMapSearch);
        List<Long> userIdInTaskList = new ArrayList<>();
        for(OwWftaskUserLink owWftaskUserLink : owWftaskUserLinkList){
            userIdInTaskList.add(owWftaskUserLink.getA2userId());
        }

        //创建业务系统中关联任务，为接收状态，发通知准备
        boolean hasUserBeenAssigned = false;
        StringBuffer sb = new StringBuffer();
        sb.append("以下人员已被分发当前任务：");
        for(Map<String,Object> map : userList) {
            String assignUserId = (String) map.get("userId");
            String owUserSupportType = (String) map.get("owUserSupportType");
            Long userIdLng = Long.parseLong(assignUserId);
            //任务处理队员中已经有这个人了
            if(userIdInTaskList.contains(userIdLng)){
                hasUserBeenAssigned = true;
                A2user a2user = a2userMapper.selectById(userIdLng);
                String a2userName = a2user.getName();
                sb.append(a2userName).append(",");
            }
        }

        if(hasUserBeenAssigned){
            return result.fault(sb.toString());
        }else {
            return result.success();
        }

    }


    /**
     向任务组中删除用户
     */
    @Override
    public Result removeGroupUserWF(Map<String,Object> paramMap){
        Result result = new Result();
        String wfTaskId = (String)paramMap.get("taskId");
        List<String> userIdList = (List<String>)paramMap.get("userIdList");

        for(String userId : userIdList){
            taskService.deleteCandidateUser(wfTaskId, userId);
        }

        return result.success();
    }


    /**
     * 待办任务
     * 查询我的任务
     */
    @Override
    public Result<OwTaskDto> queryMyTaskWF(Map<String,Object> paramMap){
        Result<OwTaskDto> result = new Result();
        String userId = (String)paramMap.get("userId");
        String owTaskType = (String)paramMap.get("owTaskType");
        Long userIdLng = Long.parseLong(userId);

        List<OwTaskDto> owTaskDtoList = new ArrayList<>();
        List<Task> taskList = taskService
                .createTaskQuery()
                .taskCandidateOrAssigned(userId).list();
        for(Task task : taskList){
            log.debug("====>");
            log.debug("taskId:" + task.getId() + ",taskName:" + task.getName() + " Assignee:"+task.getAssignee());
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            log.debug("====:" + processInstance.getBusinessKey());

            String businessKey = processInstance.getBusinessKey();
            log.debug("=====>businessKey:" + businessKey);
            String owTaskIdStr = businessKey.substring(businessKey.indexOf(':')+1);
            log.debug("=====>owTaskIdStr:" + owTaskIdStr);
            long owTaskId = Long.parseLong(owTaskIdStr);
            Result<OwTaskDto> result1 = selectById(owTaskId);
            if(!result1.isSuccess()){
                continue;
            }
            OwTaskDto owTaskDto = result1.getResultObj();
            if(owTaskDto.getDeleteflag().equals("1")){
                continue;
            }
            //查询出指定类型的任务
            if(!StringUtils.isNull(owTaskType)){
                if(!owTaskType.equals(owTaskDto.getOwTaskType())){
                    continue;
                }
            }
            String wfTaskId = task.getId();
            System.out.println("========wfTaskId"+wfTaskId);
            Long wfTaskIdLng = Long.parseLong(wfTaskId);
            //查询任务是否接收状态
            OwWftaskUserLink owWftaskUserLinkParam = new OwWftaskUserLink();
            owWftaskUserLinkParam.setA2userId(userIdLng);
            owWftaskUserLinkParam.setWfTaskId(wfTaskIdLng);
            owWftaskUserLinkParam.setIsFinished(0);
            Map<String,Object> paramMapSearch = new HashMap<>();
            paramMapSearch.put("bean",owWftaskUserLinkParam);
            List<OwWftaskUserLink> owWftaskUserLinkList = owWftaskUserLinkMapper.selectAll(paramMapSearch);
            if(owWftaskUserLinkList == null || owWftaskUserLinkList.size()==0){
                continue;
            }
            OwWftaskUserLink owWftaskUserLink = owWftaskUserLinkList.get(0);
            int hasReceiveTask = owWftaskUserLink.getHasReceiveTask();
            int owUserSupportType = owWftaskUserLink.getOwUserSupportType();
            //load to dto
            owTaskDto.setWfTaskId(wfTaskId);
            owTaskDto.getDataMap().put("wfTaskId", wfTaskId);
            owTaskDto.getDataMap().put("wfAssignee", task.getAssignee());
            owTaskDto.getDataMap().put("hasReceiveTask", String.valueOf(hasReceiveTask));//0,未接收任务，1，已接收任务
            owTaskDto.getDataMap().put("owUserSupportType", String.valueOf(owUserSupportType));//1	主办人员   2	协办人员
            owTaskDtoList.add(owTaskDto);
        }

        //如果要继续使用JDK6的排序算法
        //System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
        /*Collections.sort(owTaskDtoList, new Comparator<OwTaskDto>() {
            @Override
            public int compare(OwTaskDto o1, OwTaskDto o2) {
                return o1.getDataMap().get("hasReceiveTask").compareTo("0");
                *//*if (o1.getDataMap().get("hasReceiveTask").equalsIgnoreCase("0"))
                    return -1;
                else
                    return 1;*//*
            }
        });*/

        List<OwTaskDto> owTaskDtoList_Result = new ArrayList<>();

        List<OwTaskDto> owTaskDtoList_Result_0 = new ArrayList<>();
        for(OwTaskDto owTaskDto : owTaskDtoList){
            if (owTaskDto.getDataMap().get("hasReceiveTask").equalsIgnoreCase("0")) {
                owTaskDtoList_Result_0.add(owTaskDto);
            }
        }
        Collections.sort(owTaskDtoList_Result_0, new Comparator<OwTaskDto>() {
            @Override
            public int compare(OwTaskDto o1, OwTaskDto o2) {
                Integer o1Id = Integer.parseInt(o1.getId());
                Integer o2Id = Integer.parseInt(o2.getId());
                return -o1Id.compareTo(o2Id);
            }
        });

        List<OwTaskDto> owTaskDtoList_Result_1 = new ArrayList<>();
        for(OwTaskDto owTaskDto : owTaskDtoList){
            if (!owTaskDto.getDataMap().get("hasReceiveTask").equalsIgnoreCase("0")) {
                owTaskDtoList_Result_1.add(owTaskDto);
            }
        }
        Collections.sort(owTaskDtoList_Result_1, new Comparator<OwTaskDto>() {
            @Override
            public int compare(OwTaskDto o1, OwTaskDto o2) {
                Integer o1Id = Integer.parseInt(o1.getId());
                Integer o2Id = Integer.parseInt(o2.getId());
                return -o1Id.compareTo(o2Id);
            }
        });

        owTaskDtoList_Result.addAll(owTaskDtoList_Result_0);
        owTaskDtoList_Result.addAll(owTaskDtoList_Result_1);


        result.getResultMap().put("rows", owTaskDtoList_Result);
        result.getResultMap().put("total", owTaskDtoList_Result.size());
        return result.success();
    }



    /**
     业务系统认领任务
     */
    @Override
    public Result<OwTaskDto> claimTaskWF(OwTaskDto owTaskDto,Map<String,Object> paramMap) {
        Result<OwTaskDto> result = new Result();
        String userId = (String) paramMap.get("userId");
        String wfTaskId = owTaskDto.getWfTaskId();
        Long userIdLng = Long.parseLong(userId);
        Long wfTaskIdLng = Long.parseLong(wfTaskId);

        OwWftaskUserLink owWftaskUserLinkParam = new OwWftaskUserLink();
        owWftaskUserLinkParam.setA2userId(userIdLng);
        owWftaskUserLinkParam.setWfTaskId(wfTaskIdLng);
        Map<String,Object> paramMapSearch = new HashMap<>();
        paramMapSearch.put("bean", owWftaskUserLinkParam);
        List<OwWftaskUserLink> owWftaskUserLinkList = owWftaskUserLinkMapper.selectAll(paramMapSearch);
        OwWftaskUserLink owWftaskUserLink = owWftaskUserLinkList.get(0);
        owWftaskUserLink.setHasReceiveTask(1);
        owWftaskUserLinkMapper.updateById(owWftaskUserLink);

        //修改任务状态处理中
        OwTask owTask = new OwTask();
        owTask.setId(owWftaskUserLink.getOwTaskId());
        owTask.setOwTaskStatus(Integer.parseInt(OwTaskStatus.Doing.getKeyName().toString()));
        long i = owTaskMapper.updateTaskStatusById(owTask);
        if(i==0){
            return result.fault("修改任务状态失败");
        }

        return result.success();
    }


    /**
     * 查询任务认领情况
     * number_total，一条任务共派给几个人
     * number_hasReceiveTask，有几条已认领
     * @return
     */
    @Override
    public Result queryClaimTaskNumber(long owTaskId){
        Result result = new Result();

        OwWftaskUserLink owWftaskUserLinkParam = new OwWftaskUserLink();
        owWftaskUserLinkParam.setOwTaskId(owTaskId);
        Map<String,Object> paramMapSearch = new HashMap<>();
        paramMapSearch.put("bean", owWftaskUserLinkParam);
        List<OwWftaskUserLink> owWftaskUserLinkList = owWftaskUserLinkMapper.selectAll(paramMapSearch);
        result.getResultMap().put("number_total",owWftaskUserLinkList.size());

        owWftaskUserLinkParam = new OwWftaskUserLink();
        owWftaskUserLinkParam.setOwTaskId(owTaskId);
        owWftaskUserLinkParam.setHasReceiveTask(1);
        paramMapSearch = new HashMap<>();
        paramMapSearch.put("bean", owWftaskUserLinkParam);
        owWftaskUserLinkList = owWftaskUserLinkMapper.selectAll(paramMapSearch);
        result.getResultMap().put("number_hasReceiveTask",owWftaskUserLinkList.size());

        owWftaskUserLinkParam = new OwWftaskUserLink();
        owWftaskUserLinkParam.setOwTaskId(owTaskId);
        owWftaskUserLinkParam.setIsFinished(1);
        paramMapSearch = new HashMap<>();
        paramMapSearch.put("bean", owWftaskUserLinkParam);
        owWftaskUserLinkList = owWftaskUserLinkMapper.selectAll(paramMapSearch);
        result.getResultMap().put("number_finish",owWftaskUserLinkList.size());

        return result.success();
    }

    @Override
    public Result queryTaskListWithoutLogin(OwTaskDto owTaskDto, PageDto pageDto) {

        Result result = new Result();
        Result<OwTaskDto> owTaskDtoResult = this.paginationWithoutLogin(owTaskDto, pageDto);

        List<OwTaskDto> OwTaskDtosList = (List<OwTaskDto>)owTaskDtoResult.getResultMap().get("rows");
        Object total = owTaskDtoResult.getResultMap().get("total");
        List<Map<String,Object>> listMap = new ArrayList<>();
        result.getResultMap().put("total",total);
        for(int i=0;i<OwTaskDtosList.size();i++){
            Map<String, Object> resultMap = new HashMap<>();
            OwTaskDto owTaskDto1 = OwTaskDtosList.get(i);
            resultMap.put("owTaskDto",owTaskDto1);
            String taskNumber = owTaskDto1.getTaskNumber();

            List<OwTaskAnswer> owTaskAnswers = owTaskAnswerMapper.selectByTaskNumber(taskNumber);
            List<OwTaskAnswerDto> owTaskAnswerDtoList = new ArrayList<>();

            for(int j=0;j<owTaskAnswers.size();j++){
                OwTaskAnswer owTaskAnswer = owTaskAnswers.get(j);
                OwTaskAnswerDto owTaskAnswerDto = mapper.map(owTaskAnswer, OwTaskAnswerDto.class);
                owTaskAnswerDtoList.add(owTaskAnswerDto);

            }
            if(owTaskAnswerDtoList!=null){
                resultMap.put("owTaskAnswers",owTaskAnswerDtoList);
            }

            List<OwIssueDeclare> owIssueDeclares = owIssueDeclareMapper.selectByTaskNumber(taskNumber);
            List<OwIssueDeclareDto> owIssueDeclareDtoList = new ArrayList<>();
            for(int j=0;j<owIssueDeclares.size();j++){
                OwIssueDeclare owIssueDeclare = owIssueDeclares.get(j);
                OwIssueDeclareDto owIssueDeclareDto = mapper.map(owIssueDeclare, OwIssueDeclareDto.class);
                owIssueDeclareDtoList.add(owIssueDeclareDto);

            }
            if(owTaskAnswerDtoList!=null){
                resultMap.put("owIssueDeclares",owIssueDeclareDtoList);
            }
            listMap.add(resultMap);
        }

        result.setResultList(listMap);
        return result.success();
    }

    /**
     完成我的任务，录入一些信息
     */
    @Override
    public Result<OwTaskDto> dealMyTaskWF(OwTaskDto owTaskDto,Map<String,Object> paramMap){
        Result<OwTaskDto> result = new Result();
        String userId = (String)paramMap.get("userId");
        A2user a2user = a2userMapper.selectById(Long.parseLong(userId));
        log.debug("=========>userId:" + userId);
        log.debug("=========>a2user.getName:" + a2user.getName());

        OwTask owTask = owTaskMapper.selectById(Long.parseLong(owTaskDto.getId()));

        //如果任务已完成状态，直接记录一下结果
        OwTaskAnswer owTaskAnswer = new OwTaskAnswer();
        owTaskAnswer.setA2userId(Long.parseLong(userId));
        owTaskAnswer.setOwTaskId(owTask.getId());
        owTaskAnswer.setOwTaskType(owTask.getOwTaskType());
        owTaskAnswer.setImproveRequied(owTask.getImproveRequied());
        owTaskAnswer.setIssueContent(owTask.getIssueContent());
        owTaskAnswer.setRemark(owTask.getRemark());
        owTaskAnswer.setAssistManName(owTask.getAssistManName());
        owTaskAnswer.setMainManName(owTask.getMainManName());
        owTaskAnswer.setAssistManId(owTask.getAssistManId());
        owTaskAnswer.setMainManId(owTask.getMainManId());
        owTaskAnswer.setLitigantName(owTask.getLitigantName());
        owTaskAnswer.setLitigantPhone(owTask.getLitigantPhone());
        owTaskAnswer.setPosDesc(owTask.getPosDesc());
        owTaskAnswer.setPosHouseNumber(owTask.getPosHouseNumber());
        owTaskAnswer.setPosLat(owTask.getPosLat());
        owTaskAnswer.setPosLng(owTask.getPosLng());
        owTaskAnswer.setBaseCommiteeId(owTask.getBaseCommiteeId());
        owTaskAnswer.setBaseRoadId(owTask.getBaseRoadId());
        owTaskAnswer.setFinderDeptName(owTask.getFinderDeptName());
        owTaskAnswer.setFinderDeptId(owTask.getFinderDeptId());
        owTaskAnswer.setOwRegisterType(owTask.getOwRegisterType());
        owTaskAnswer.setOwViolationType(owTask.getOwViolationType());
        owTaskAnswer.setOwTaskType(owTask.getOwTaskType());
        owTaskAnswer.setName(owTask.getName());
        owTaskAnswer.setOwPriorityCode(owTask.getOwPriorityCode());
        owTaskAnswer.setRegisterDataNumber(owTask.getRegisterDataNumber());
        owTaskAnswer.setTaskNumber(owTask.getTaskNumber());
        //
        owTaskAnswer.setOwDealType(Integer.parseInt(owTaskDto.getOwDealType()));
        owTaskAnswer.setDealIssueContent(owTaskDto.getDealIssueContent());
        owTaskAnswer.setDealResult(owTaskDto.getDealResult());
        owTaskAnswer.setDealRemark(owTaskDto.getDealRemark());
        if (!StringUtils.isNull(owTaskDto.getDealTime())) {
            owTaskAnswer.setDealTime(DateTool.str2Timestamp(owTaskDto.getDealTime()));
        }
        owTaskAnswer.setOwTaskStatus(Integer.parseInt(OwTaskStatus.Done.getKeyName().toString()));
        owTaskAnswer.setCompanyId(0);
        owTaskAnswer.setDeleteflag(0);
        owTaskAnswer.setCreatedate(DateTool.getCurTimestamp());
        owTaskAnswer.setCreatemanId(Integer.parseInt(userId));
        owTaskAnswer.setCreateman(a2user.getName());
        //处理人签名 2020-01-02
        owTaskAnswer.setSignPic(owTaskDto.getSignPic());
        owTaskAnswerMapper.insert(owTaskAnswer);
        if(owTaskDto!=null && owTaskDto.getOwPictureMagDtoList()!=null) {
            for (OwPictureMagDto owPictureMagDto : owTaskDto.getOwPictureMagDtoList()) {
                OwPictureMag owPictureMag = mapper.map(owPictureMagDto, OwPictureMag.class);
                //1:front, 2:back （默认设1）
                owPictureMag.setFrontBackSort(
                        StringUtils.isNull(owPictureMagDto.getFrontBackSort())?1:Integer.parseInt(owPictureMagDto.getFrontBackSort()));
                owPictureMag.setOwTableType("ow_task_answer_id");
                owPictureMag.setOwTableId(owTaskAnswer.getId());
                owPictureMag.setCompanyId(0);
                owPictureMag.setCreatemanId(0);
                owPictureMag.setModifymanId(0);
                owPictureMagMapper.insert(owPictureMag);
            }
        }
        if(owTask.getOwTaskStatus() == Integer.parseInt(OwTaskStatus.Done.getKeyName().toString())){
            //start: 系统演示，加入这块代码，以后可去掉。2019.1.29
            String wfTaskId = owTaskDto.getWfTaskId();
            Long wfTaskIdLng = Long.parseLong(wfTaskId);
            OwWftaskUserLink owWftaskUserLinkParam = new OwWftaskUserLink();
            owWftaskUserLinkParam.setWfTaskId(wfTaskIdLng);
            Map<String,Object> paramMapSearch = new HashMap<>();
            paramMapSearch.put("bean",owWftaskUserLinkParam);
            List<OwWftaskUserLink> owWftaskUserLinkList = owWftaskUserLinkMapper.selectAll(paramMapSearch);
            for(OwWftaskUserLink owWftaskUserLink : owWftaskUserLinkList){
                owWftaskUserLink.setIsFinished(1);
                owWftaskUserLinkMapper.updateById(owWftaskUserLink);
            }
            //end

            return result.success();
        }

        //更新信息
        owTask.setOwDealType(Integer.parseInt(owTaskDto.getOwDealType()));
        owTask.setDealIssueContent(owTaskDto.getDealIssueContent());
        owTask.setDealResult(owTaskDto.getDealResult());
        owTask.setDealRemark(owTaskDto.getDealRemark());
        if(!StringUtils.isNull(owTaskDto.getDealTime())) {
            owTask.setDealTime(DateTool.str2Timestamp(owTaskDto.getDealTime()));
        }
        owTaskMapper.updateById(owTask);

        //插入多张图片
        if(owTaskDto!=null && owTaskDto.getOwPictureMagDtoList()!=null) {
            for (OwPictureMagDto owPictureMagDto : owTaskDto.getOwPictureMagDtoList()) {
                OwPictureMag owPictureMag = mapper.map(owPictureMagDto, OwPictureMag.class);
                //1:front, 2:back （默认设1）
                owPictureMag.setFrontBackSort(
                        StringUtils.isNull(owPictureMagDto.getFrontBackSort())?1:Integer.parseInt(owPictureMagDto.getFrontBackSort()));
                owPictureMag.setOwTableType("ow_task_id");
                owPictureMag.setOwTableId(owTask.getId());
                owPictureMag.setCompanyId(0);
                owPictureMag.setCreatemanId(0);
                owPictureMag.setModifymanId(0);
                owPictureMagMapper.insert(owPictureMag);
            }
        }

        String wfTaskId = owTaskDto.getWfTaskId();
        Long wfTaskIdLng = Long.parseLong(wfTaskId);

        OwWftaskUserLink owWftaskUserLinkParam = new OwWftaskUserLink();
        owWftaskUserLinkParam.setWfTaskId(wfTaskIdLng);
        Map<String,Object> paramMapSearch = new HashMap<>();
        paramMapSearch.put("bean",owWftaskUserLinkParam);
        List<OwWftaskUserLink> owWftaskUserLinkList = owWftaskUserLinkMapper.selectAll(paramMapSearch);
        for(OwWftaskUserLink owWftaskUserLink : owWftaskUserLinkList){
            owWftaskUserLink.setIsFinished(1);
            owWftaskUserLinkMapper.updateById(owWftaskUserLink);
        }

        //修改任务状态处理完成
        OwTask owTaskParam = new OwTask();
        owTaskParam.setId(owTask.getId());
        owTaskParam.setOwTaskStatus(Integer.parseInt(OwTaskStatus.Done.getKeyName().toString()));
        long i = owTaskMapper.updateTaskStatusById(owTaskParam);
        if(i==0){
            return result.fault("修改任务状态失败");
        }

        //工作流中的任务不做结束处理
        if(existTask(wfTaskId,userId)) {
            //认领任务
            taskService.claim(wfTaskId, userId);
            //完成任务
            taskService.setVariable(wfTaskId, "owTaskType", owTask.getOwTaskType());
            taskService.complete(wfTaskId);
        }

        return result.success();
    }

    /**
     * 用户名下是否存在任务
     * @param wfTaskId
     * @param userId
     * @return
     */
    private boolean existTask(String wfTaskId, String userId){
        List<Task> taskList = taskService
                .createTaskQuery()
                .taskCandidateOrAssigned(userId).list();
        for(Task taskTmp : taskList) {
            long wftaskid_tmp = Long.parseLong(taskTmp.getId());
            long wfTaskId_lng = Long.parseLong(wfTaskId);
            if(wfTaskId_lng == wftaskid_tmp){
                return true;
            }
        }
        return false;
    }

    /**
     * 已办任务
     * 查询已完成 我的任务
     */
    @Override
    public Result<OwTaskAnswerDto> queryCompletedMyTaskWF(Map<String,Object> paramMap,OwTaskDto owTaskDto,PageDto pageDto){
        Result<OwTaskAnswerDto> result = new Result();
        String userId = (String)paramMap.get("userId");
        String owTaskType = owTaskDto.getOwTaskType();
        log.debug("=======>userId:"+userId);
        log.debug("=======>owTaskType:" + owTaskType);

        OwTaskAnswerDto owTaskAnswerDto = new OwTaskAnswerDto();
        owTaskAnswerDto.setA2userId(userId);
        if(!StringUtils.isNull(owTaskType)){
            owTaskAnswerDto.setOwTaskType(owTaskType);
        }
        pageDto.setSortColumn("createdate");
        pageDto.setSortOrder("desc");
        result = owTaskAnswerService.pagination(owTaskAnswerDto, pageDto);

        return result;
    }





/*

    */
/**
     查询已完成 我的任务
     *//*

    @Override
    public Result<OwTaskDto> queryCompletedMyTaskWF(Map<String,Object> paramMap,OwTaskDto owTaskDto,PageDto pageDto){
        Result<OwTaskDto> result = new Result();
        String userId = (String)paramMap.get("userId");
        String owTaskType = owTaskDto.getOwTaskType();
        log.debug("=======>userId:"+userId);
        log.debug("=======>owTaskType:"+owTaskType);

        List<OwTaskDto> owTaskDtoList = new ArrayList<>();
        ////查询出指定类型的任务
        HistoricTaskInstanceQuery historicTaskInstanceQuery = null;
        if(StringUtils.isNull(owTaskType)){
            historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery()
                    .taskAssignee(userId).finished()
                    .orderByTaskCreateTime().desc();
        }else{
            historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery()
                    .taskAssignee(userId).finished()
                    .orderByTaskCreateTime().desc()
                    .processVariableValueEquals("owTaskType", Integer.parseInt(owTaskType));
        }
        List<HistoricTaskInstance> historicTaskInstanceList =  historicTaskInstanceQuery
                .listPage(pageDto.getPageIndex(),pageDto.getPageSize());
        long total =  historicTaskInstanceQuery.count();
        log.debug("<======total:"+total);

        for(HistoricTaskInstance historicTaskInstance : historicTaskInstanceList){
            String processInstanceId = historicTaskInstance.getProcessInstanceId();
            log.debug("=====>processInstanceId:" + processInstanceId);
            HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(processInstanceId).singleResult();
            log.debug("=====>processInstance:"+processInstance);
            if(processInstance==null)continue;
            String businessKey = processInstance.getBusinessKey();
            log.debug("=====>businessKey:" + businessKey);
            String owTaskIdStr = businessKey.substring(businessKey.indexOf(':')+1);
            log.debug("=====>owTaskIdStr:" + owTaskIdStr);
            long owTaskId = Long.parseLong(owTaskIdStr);
            OwTaskDto owTaskDto1 = selectById(owTaskId).getResultObj();
            if(owTaskDto1.getDeleteflag().equals("1"))continue;
            owTaskDtoList.add(owTaskDto1);
        }

        result.getResultMap().put("rows", owTaskDtoList);
        result.getResultMap().put("total", total);

        return result.success();
    }
*/

    /**
     我指派的任务
     */
    @Override
    public Result<OwTaskDto> queryMyApplyTaskWF(Map<String,Object> paramMap){
        Result<OwTaskDto> result = new Result();
        String userId = (String)paramMap.get("userId");

        List<OwTaskDto> owTaskDtoList = new ArrayList<>();
        List<HistoricProcessInstance> historicTaskInstanceList = historyService.createHistoricProcessInstanceQuery()
                .startedBy(userId).orderByProcessInstanceStartTime().desc().list();
        log.debug("========>historicTaskInstanceList.size:"+historicTaskInstanceList.size());
        for(HistoricProcessInstance historicProcessInstance : historicTaskInstanceList){
            String processInstanceId = historicProcessInstance.getId();
            log.debug("=====>processInstanceId:"+processInstanceId);
            String businessKey = historicProcessInstance.getBusinessKey();
            log.debug("=====>businessKey:" + businessKey);
            String owTaskIdStr = businessKey.substring(businessKey.indexOf(':')+1);
            log.debug("=====>owTaskIdStr:" + owTaskIdStr);
            long owTaskId = Long.parseLong(owTaskIdStr);
            Result<OwTaskDto> result1 = selectById(owTaskId);
            if(!result1.isSuccess()){
                continue;
            }
            OwTaskDto owTaskDto = result1.getResultObj();
            if(owTaskDto.getDeleteflag().equals("1")){
                continue;
            }
            //owTaskDto.setWfTaskId(historicProcessInstance.getId());
            owTaskDtoList.add(owTaskDto);
        }

        result.getResultMap().put("rows", owTaskDtoList);
        result.getResultMap().put("total", owTaskDtoList.size());

        return result.success();
    }


    /**
     完成我的任务
     */
    @Override
    public Result completeMyTaskWF(Map<String,Object> paramMap){
        Result result = new Result();
        /*String taskId = (String)paramMap.get("taskId");


        //taskService.setVariable(taskId, "managerUserIds", "1");
        //完成任务
        String wfTaskId = owTaskDto.getWfTaskId();
        taskService.setVariable(taskId,"owTaskType",owTask.getOwTaskType());
        taskService.complete(wfTaskId);

        taskService.complete(taskId);*/

        return result.success();
    }









}
